/**
 * 
 */
package com.ai.notices.web;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.ai.notices.dao.mysql.model.IdentityCard;

import net.sf.json.JSONObject;

/**
 * @author 文件工具类
 *
 */
public class FileUtils {
	
    private static final Logger log = Logger.getLogger(FileUtils.class);
    
	public static boolean isExcel2003(String filePath) {
		return filePath.matches("^.+\\.(?i)(xls)$");
	}
	
	public static boolean isExcel2007(String filePath) {
		return filePath.matches("^.+\\.(?i)(xlsx)$");
	}
	
	@SuppressWarnings("resource")
	public static List<List<Map<String, String>>> file2List(MultipartFile mfile) throws IOException {
		if (mfile == null) {
			return Collections.emptyList();
		}
		Workbook workBook = null;
		String strFileNmae = mfile.getOriginalFilename();
		if (FileUtils.isExcel2003(strFileNmae)) {
			workBook = new HSSFWorkbook(mfile.getInputStream());
		} else if (FileUtils.isExcel2007(strFileNmae)) {
			workBook = new XSSFWorkbook(mfile.getInputStream());
		} else {
			return Collections.emptyList();
		}
		List<List<Map<String, String>>> result = new ArrayList<>();
		int nSheetNumber = workBook.getNumberOfSheets();
		nSheetNumber = 1;// 暂时只读取第一页
		for (int i = 0; i < nSheetNumber; i++) {
			result.add(excel2List(workBook.getSheetAt(i)));
		}
		return result;
	}
	
	public static List<Map<String, String>> excel2List(Sheet sheet) {
		if (sheet.getLastRowNum() < 1) {
			return Collections.emptyList();
		}
		List<Map<String, String>> result = new ArrayList<>();
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Map<String, String> sheetMap = new HashMap<>();
			Row row = sheet.getRow(i);
			if (StringUtils.isBlank(getStringVal(row.getCell(0)))) {
				continue;
			}
			for (int j = 0; j < row.getLastCellNum(); j++) {
				sheetMap.put(String.valueOf(j), getStringVal(row.getCell(j)));
			}
			result.add(sheetMap);
		}
		return result;
	}
	
	public static String getStringVal(Cell cell) {
		if(null == cell){
			return "";
		}else{
			switch (cell.getCellTypeEnum()) {
				case BOOLEAN:
					return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
				case FORMULA:
					return cell.getCellFormula();
				case NUMERIC:
					Object inputValue = null;
					Long longVal = Math.round(cell.getNumericCellValue());
					Double doubleVal = cell.getNumericCellValue();
					if(Double.parseDouble(longVal+".0")==doubleVal){
						inputValue = longVal;
					}else{
						inputValue = doubleVal;
					}
					DecimalFormat df = new DecimalFormat("#.###");    //格式化为四位小数，按自己需求选择；
					return String.valueOf(df.format(inputValue));
				case STRING:
					return cell.getStringCellValue();
				default:
					return "";
			}
		}
	}
	
	public static String getId() {
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
		Random random = new Random();
		int result = random.nextInt(900)+100;
		return sf.format(date)+String.valueOf(result);
    }
	
	public static String getRandomId() {
		Random random = new Random();
        int randomId = random.nextInt(9000000)+1000000;
		int result = random.nextInt(9000)+1000;
		return String.valueOf(randomId)+String.valueOf(result);
    }
	
	public static String getIdCard(IdentityCard identityCard) {
		String host = "http://aliyunverifyidcard.haoservice.com";
	    String path = "/idcard/VerifyIdcardv2";
	    String method = "GET";
	    String appcode = "5d57496568294ba98f959df8b91e3c58";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    Map<String, String> querys = new HashMap<String, String>();
	    querys.put("cardNo", identityCard.getIdentityCard());
	    querys.put("realName", identityCard.getName());

	    try {
	    	/**
	    	* 重要提示如下:
	    	* HttpUtils请从
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
	    	* 下载
	    	*
	    	* 相应的依赖请参照
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
	    	*/
	    	log.error("/idcard/VerifyIdcardv2请求========cardNo:"+querys.get("cardNo")+"==========realName:"+querys.get("realName"));
	    	HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
	    	log.error("/idcard/VerifyIdcardv2返回response=================="+response.toString());
	    	String result = EntityUtils.toString(response.getEntity());
//	    	String result = "{\"error_code\":0,\"reason\":\"成功\",\"result\":{\"realname\":\"孙尹\",\"idcard\":\"420602198206201511\",\"isok\":true,\"IdCardInfor\":{\"area\":\"湖北省襄樊市襄城区\",\"sex\":\"男\",\"birthday\":\"1982-6-20\"}}}";
	    	JSONObject jsonObject = JSONObject.fromObject(result);
	    	log.error("/idcard/VerifyIdcardv2返回Entity=================="+result);
	    	String error_code = jsonObject.getString("error_code");
	    	if (!"0".equals(error_code)) {
	    		return error_code;
	    	}
	    	JSONObject JSONResult = jsonObject.getJSONObject("result");
	    	return JSONResult.getString("isok");
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	log.error(e.getMessage());
	    }
	    return "error";
    }
}
